const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});

const server = http.createServer(app);
const io = socketIo(server, {
    cors: {
        origin: "http://127.0.0.1:5500",
        methods: ["GET", "POST"],
        allowedHeaders: ["Content-Type", "Authorization"],
        credentials: true
    }
});

const roomOwners = new Map(); // 存储每个房间的房主

io.on('connection', socket => {
    console.log('New client connected:', socket.id);

    socket.on('joinRoom', room => {
        socket.join(room);
        const roomClients = io.sockets.adapter.rooms.get(room) || new Set();
        console.log(`Users in room ${room}:`, Array.from(roomClients));

        // 设置房主：第一个加入房间的用户为房主
        if (!roomOwners.has(room)) {
            roomOwners.set(room, socket.id);
            socket.emit('setRoomOwner', true);
            console.log(`Set ${socket.id} as owner of room ${room}`);
        } else {
            socket.emit('setRoomOwner', false);
        }

        socket.broadcast.to(room).emit('userJoined', socket.id);
        console.log(`User ${socket.id} joined room ${room}`);
    });

    socket.on('offer', (id, description) => {
        console.log(`Offer from ${socket.id} to ${id}`);
        socket.to(id).emit('offer', socket.id, description);
    });

    socket.on('answer', (id, description) => {
        console.log(`Answer from ${socket.id} to ${id}`);
        socket.to(id).emit('answer', socket.id, description);
    });

    socket.on('candidate', (id, candidate) => {
        console.log(`Candidate from ${socket.id} to ${id}`);
        socket.to(id).emit('candidate', socket.id, candidate);
    });

    socket.on('chat', (userId, message) => {
        console.log(`Chat received from ${userId} in room: ${Array.from(socket.rooms)[0]}, message: ${message}`);
        const room = Array.from(socket.rooms)[0];
        io.to(room).emit('chat', userId, message);
    });

    socket.on('muteAllMic', (room) => {
        console.log(`Mute all mics command from ${socket.id} in room ${room}`);
        if (roomOwners.get(room) === socket.id) {
            io.to(room).emit('muteAllMic');
        }
    });

    socket.on('muteAllVideo', (room) => {
        console.log(`Mute all videos command from ${socket.id} in room ${room}`);
        if (roomOwners.get(room) === socket.id) {
            io.to(room).emit('muteAllVideo');
        }
    });

    socket.on('disconnect', () => {
        console.log('Client disconnected:', socket.id);
        // 如果房主断开连接，移除房主记录
        for (const [room, ownerId] of roomOwners.entries()) {
            if (ownerId === socket.id) {
                roomOwners.delete(room);
                console.log(`Room owner ${socket.id} left room ${room}`);
                break;
            }
        }
    });
});

const PORT = process.env.PORT || 4000;
server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));